package com.globaldom.web.locations;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.globaldom.model.CivResource;
import com.globaldom.model.CountryDetail;
import com.globaldom.model.MilResource;
import com.globaldom.model.Person;
import com.globaldom.model.PersonLocation;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

@Controller
@RequestMapping("/location")
public class LocationController {

	private static final Logger log = Logger.getLogger(LocationController.class.getName());

	public LocationController() {
	}

	@RequestMapping(method = RequestMethod.GET)
	public String redir() {
		return "redirect:/" + Constants.gamepage;
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String storeLocation(@RequestParam String cCode, @RequestParam float lat, @RequestParam float lon,
			Model model, HttpServletRequest request, HttpSession session) throws Exception {
		String personID = SessionManager.getID(request, session);
		if (null == personID) {
			return "redirect:/" + Constants.mainpage;

		}

		PersistenceManager pmf = PMF.get().getPersistenceManager();
		try {

			Person person = pmf.getObjectById(Person.class, personID);
			CountryDetail cd = CountryDetail.findByCountryCode(cCode);
			// If either the person doesn't exist or the country is invalid then
			// return back to country selection
			if (null == person || null == cd) {
				log.log(Level.SEVERE, " Country is null!!! redirecting to country. Possible infinite loop: code"
						+ cCode);
				return "redirect:/" + Constants.mainpage;
			}

			person.setCountryCode(cd.getId().intValue());
			PersonLocation pl = new PersonLocation();
			pl.setLocationType(0);
			pl.setLatitude(lat);
			pl.setLongitude(lon);
			pl.setDateCreated(new Date());
			pl.setPerson(personID);
			PersistenceManager pmloc = PMF.get().getPersistenceManager();
			pmloc.makePersistent(pl);
			pmloc.close();

			List<CivResource> allres = new ArrayList<CivResource>();
			CivResource resFood = new CivResource();
			resFood.setId(personID + "/" + CivResource.FOOD);
			resFood.setResType(CivResource.FOOD);
			resFood.setCivDeployed(6);
			resFood.setResAvailable(6000L);
			resFood.setResourceUpdated(new Date());
			resFood.setPerson(personID);
			allres.add(resFood);

			CivResource resWater = new CivResource();
			resWater.setId(personID + "/" + CivResource.WATER);
			resWater.setResType(CivResource.WATER);
			resWater.setCivDeployed(5);
			resWater.setResAvailable(5000L);
			resWater.setResourceUpdated(new Date());
			resWater.setPerson(personID);
			allres.add(resWater);
			CivResource resOil = new CivResource();
			resOil.setId(personID + "/" + CivResource.OIL);
			resOil.setResType(CivResource.OIL);
			resOil.setCivDeployed(4);
			resOil.setResAvailable(4000l);
			resOil.setPerson(personID);
			allres.add(resOil);
			CivResource resWood = new CivResource();
			resWood.setId(personID + "/" + CivResource.WOOD);
			resWood.setResType(CivResource.WOOD);
			resWood.setCivDeployed(3);
			resWood.setResAvailable(3000L);
			resWood.setPerson(personID);
			allres.add(resWood);
			CivResource resSilver = new CivResource();
			resSilver.setId(personID + "/" + CivResource.SILVER);
			resSilver.setResType(CivResource.SILVER);
			resSilver.setCivDeployed(2);
			resSilver.setResAvailable(2000L);
			resSilver.setPerson(personID);
			allres.add(resSilver);

			CivResource resGold = new CivResource();
			resGold.setId(personID + "/" + CivResource.GOLD);
			resGold.setResType(CivResource.GOLD);
			resGold.setCivDeployed(1);
			resGold.setResAvailable(1000L);
			resGold.setPerson(personID);
			allres.add(resGold);
			CivResource resDollar = new CivResource();
			resDollar.setId(personID + "/" + CivResource.DOLLAR);
			resDollar.setResType(CivResource.DOLLAR);
			resDollar.setCivDeployed(0);
			resDollar.setResAvailable(1000L);
			resDollar.setPerson(personID);
			allres.add(resDollar);

			CivResource resKarma = new CivResource();
			resKarma.setId(personID + "/" + CivResource.KARMA);
			resKarma.setResType(CivResource.KARMA);
			resKarma.setCivDeployed(0);
			resKarma.setResAvailable(2500L);
			resKarma.setPerson(personID);
			allres.add(resKarma);

			CivResource resXP = new CivResource();
			resXP.setId(personID + "/" + CivResource.XP);
			resXP.setResType(CivResource.XP);
			resXP.setCivDeployed(0);
			resXP.setResAvailable(2000L);
			resXP.setPerson(personID);
			allres.add(resXP);
			PersistenceManager pmciv = PMF.get().getPersistenceManager();
			pmciv.makePersistentAll(allres);
			pmciv.close();

			List<MilResource> milres = new ArrayList<MilResource>();
			MilResource milArmy = new MilResource();
			milArmy.setId(personID + "/" + MilResource.ARMY);
			milArmy.setUnitType(MilResource.ARMY);
			milArmy.setMilAvailable(600l);
			milArmy.setResourceUpdated(new Date());
			milArmy.setPerson(personID);
			milres.add(milArmy);

			MilResource milTank = new MilResource();
			milTank.setId(personID + "/" + MilResource.TANK);
			milTank.setUnitType(MilResource.TANK);
			milTank.setMilAvailable(500l);
			milTank.setResourceUpdated(new Date());
			milTank.setPerson(personID);
			milres.add(milTank);

			MilResource milAir = new MilResource();
			milAir.setId(personID + "/" + MilResource.AIR);
			milAir.setUnitType(MilResource.AIR);
			milAir.setMilAvailable(400l);
			milAir.setPerson(personID);
			milAir.setResourceUpdated(new Date());
			milres.add(milAir);

			MilResource milNavy = new MilResource();
			milNavy.setId(personID + "/" + MilResource.NAVY);
			milNavy.setUnitType(MilResource.NAVY);
			milNavy.setMilAvailable(300l);
			milNavy.setPerson(personID);
			milNavy.setResourceUpdated(new Date());
			milres.add(milNavy);

			MilResource milSpies = new MilResource();
			milSpies.setId(personID + "/" + MilResource.SPIES);
			milSpies.setUnitType(MilResource.SPIES);
			milSpies.setPerson(personID);
			milSpies.setMilAvailable(200l);
			milSpies.setResourceUpdated(new Date());
			milres.add(milSpies);

			MilResource milSubs = new MilResource();
			milSubs.setId(personID + "/" + MilResource.SUB);
			milSubs.setUnitType(MilResource.SUB);
			milSubs.setPerson(personID);
			milSubs.setMilAvailable(100l);
			milSubs.setResourceUpdated(new Date());
			milres.add(milSubs);
			PersistenceManager pmmil = PMF.get().getPersistenceManager();
			pmmil.makePersistentAll(milres);
			pmmil.close();

			Queue queue = QueueFactory.getDefaultQueue();
			TaskOptions taskOptions = TaskOptions.Builder.withUrl("/stats/updatelocations")
					.param("personid", personID.toString()).param("countryid", cCode.toString());
			taskOptions.method(Method.GET);
			queue.add(taskOptions);
			session.setAttribute("firsttime", "true");

		} catch (Exception ex) {
			log.log(Level.SEVERE, "Exception while trying to store the person!" + ex.getMessage());
			return "redirect:/" + Constants.mainpage;
		} finally {
			pmf.close();
		}

		return "redirect:/resource";
	}
}